package push.service;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.example.xuegengwang.xuegengwang.MainActivity;
import com.example.xuegengwang.xuegengwang.R;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTTransmitMessage;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;

import common.Constant;
import common.MyApplication;
import fourFragment.activity.MyQuestion;
import https.InterNetController;
import pay.activity.EnCash;
import question.activity.QuestionDetail;
import question.activity.VipQuestionDetail;
import utils.MyLogUtils;
import utils.SPUtils;
import utils.ToastUtils;
import utils.VariousUtils;
import view.MyConfirmDialog;
import willevaluate.activity.ExpertEvaluate;

/**
 * Created by Administrator on 2017/4/20.
 * 推送服务,要写逻辑代码
 */

public class MyIntentService extends GTIntentService {

    private boolean isDialogShow = false;
    View notification_window;
    TextView notification_window_text;
    LinearLayout notification_window_layout;
    WindowManager mWindowManager;
    WindowManager.LayoutParams params;
    private MyHandler1 myHandler1;

    private class MyHandler1 extends Handler {
        WeakReference<MyIntentService> weakReference;

        public MyHandler1(MyIntentService service) {
            weakReference = new WeakReference<>(service);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 20:
                    if (isRunningForeground(MyIntentService.this.getApplicationContext())) {
                        MyLogUtils.e(TAG, "in");
                        try {
                            showDialog((String) msg.obj);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        MyLogUtils.e(TAG, "out");
                        try {
                            showNotification((String) msg.obj);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        myHandler1 = new MyHandler1(this);
        notification_window = LayoutInflater.from(MyIntentService.this).inflate(R.layout.notification_window, null);
        notification_window_text = (TextView) notification_window.findViewById(R.id.notification_window_text);
        notification_window_layout = (LinearLayout) notification_window.findViewById(R.id.notification_window_layout);
        mWindowManager = (WindowManager) MyIntentService.this.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        params = new WindowManager.LayoutParams();
    }

    public MyIntentService() {

    }

    @Override
    public void onReceiveServicePid(Context context, int pid) {
        MyLogUtils.e(TAG, "onReceiveServicePid -> " + "pid = " + pid);
    }

    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        String command = new String(msg.getPayload());
        MyLogUtils.e(TAG, "onReceiveMessageData -> " + command);
        Message message = new Message();
        message.what = 20;
        message.obj = command;
        myHandler1.sendMessage(message);
    }

    @Override
    public void onReceiveClientId(Context context, String clientid) {
        MyLogUtils.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid);
        SharedPreferences.Editor edit = SPUtils.getSharedPreferences().edit();
        edit.putString(Constant.CLIENTID, clientid);
        edit.commit();
    }

    @Override
    public void onReceiveOnlineState(Context context, boolean online) {
        MyLogUtils.e(TAG, "onReceiveOnlineState -> " + "online = " + online);
    }

    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
        MyLogUtils.e(TAG, "onReceiveCommandResult -> " + "cmdMessage = " + cmdMessage);
    }

    //弹窗
    private void showDialog(final String msg) throws JSONException {
        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
        params.format = PixelFormat.TRANSLUCENT;
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.TOP | Gravity.LEFT;
        JSONObject jsonObject = new JSONObject(msg);
        final String target = jsonObject.getString("target");
        final String message = jsonObject.getString("message");
        final Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
        MyLogUtils.e(TAG, target);
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {

            }

            @Override
            public void updateDrawState(TextPaint ds) {
                int color = MyIntentService.this.getResources().getColor(R.color.common_color);
                ds.setColor(color);
                ds.setUnderlineText(false);
            }
        };
        SpannableString spannableString = new SpannableString(message + "点击查看");
        spannableString.setSpan(clickableSpan, message.length(), (message + "点击查看").length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        notification_window_text.setText(spannableString);
        switch (target) {
            case "account":
                notifyPersonalInfo();
                formatMoney(intent, jsonObject);
                break;
            case "dialogdetail":
                notifyPersonalInfo();
                formatDialog(intent, jsonObject);
                break;
            case "Submit":
                //志愿填报推送
                formatSubmit(intent, jsonObject);
                break;
            default:
                break;
        }
        notification_window_layout.setOnClickListener(new View.OnClickListener() {
                                                          @Override
                                                          public void onClick(View v) {
                                                              notification_window_layout.setClickable(false);
                                                              startActivity(intent);
                                                              closeNotification();
                                                          }
                                                      }
        );
        final Handler handler1 = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                closeNotification();
            }
        };

        if (!isDialogShow) {
            mWindowManager.addView(notification_window, params);
            Animation animation = AnimationUtils.loadAnimation(MyIntentService.this, R.anim.up_to_down);
            animation.setDuration(500);
            animation.setRepeatMode(Animation.INFINITE);
            animation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(3000);
                                Message message = new Message();
                                handler1.sendMessage(message);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            notification_window_layout.startAnimation(animation);
            isDialogShow = true;
        }

        notification_window.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        notification_window.setClickable(false);
                        closeNotification();
                    }
                }
        );
    }

    //关闭弹窗
    private void closeNotification() {
        if (isDialogShow) {
            Animation animation = AnimationUtils.loadAnimation(MyIntentService.this, R.anim.down_to_up);
            animation.setDuration(500);
            animation.setRepeatMode(Animation.INFINITE);
            notification_window_layout.startAnimation(animation);
            animation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    mWindowManager.removeView(notification_window);
                    isDialogShow = false;
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
    }

    //弹出通知栏
    private void showNotification(String msg) throws JSONException {
        NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification();
        // 设置显示在手机最上边的状态栏的图标
        notification.icon = R.mipmap.ic_launcher;
        // 当前的notification被放到状态栏上的时候，提示内容
        JSONObject jsonObject = new JSONObject(msg);
        String target = jsonObject.getString("target");
        String message = jsonObject.getString("message");
        RemoteViews remoteView = new RemoteViews(this.getPackageName(), R.layout.notification_window);
        notification.defaults = Notification.DEFAULT_SOUND;
        notification.when = System.currentTimeMillis();
        notification.ledARGB = Color.BLUE;
        notification.ledOnMS = 1000;
        notification.ledOffMS = 1000;
        notification.flags = Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_AUTO_CANCEL;
        notification.tickerText = message;
        remoteView.setImageViewResource(R.id.image, R.mipmap.ic_launcher);
        notification.contentView = remoteView;
        notification.audioStreamType = android.media.AudioManager.ADJUST_LOWER;
        PendingIntent contentIntent = null;
        remoteView.setTextViewText(R.id.notification_window_text, message + "点击查看");
        switch (target) {
            case "account"://余额变动
                notifyPersonalInfo();
                Intent[] intents1 = new Intent[2];
                intents1[0] = Intent.makeRestartActivityTask(new ComponentName(this, MainActivity.class));
                intents1[0].setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                intents1[0].putExtra("drump", 4);
                intents1[1] = new Intent();
                intents1[1].setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
                formatMoney(intents1[1], jsonObject);
                contentIntent = PendingIntent.getActivities(this, 0, intents1, PendingIntent.FLAG_UPDATE_CURRENT);
                break;
            case "dialogdetail"://问题变动
                notifyPersonalInfo();
                Intent[] intents2 = new Intent[3];
                intents2[0] = Intent.makeRestartActivityTask(new ComponentName(this, MainActivity.class));
                intents2[0].setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                intents2[0].putExtra("drump", 4);
                intents2[1] = new Intent(this, MyQuestion.class);
                intents2[1].setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
                intents2[2] = new Intent();
                intents2[2].setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
                formatDialog(intents2[2], jsonObject);
                contentIntent = PendingIntent.getActivities(this, 0, intents2, PendingIntent.FLAG_UPDATE_CURRENT);
                break;
            case "Submit"://志愿填报变动
                Intent[] intents3 = new Intent[2];
                intents3[0] = Intent.makeRestartActivityTask(new ComponentName(this, MainActivity.class));
                intents3[0].setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intents3[1] = new Intent();
                intents3[1].setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
                formatSubmit(intents3[1], jsonObject);
                contentIntent = PendingIntent.getActivities(this, 0, intents3, PendingIntent.FLAG_UPDATE_CURRENT);
                break;
            default:
                break;
        }
        if (contentIntent != null) {
            notification.contentIntent = contentIntent;
            manager.notify(0, notification);
        } else {
            MyLogUtils.e(TAG, "null");
        }
    }

    //志愿填报解析
    private void formatSubmit(Intent intent, JSONObject jsonObject) throws JSONException {
        intent.setAction("Submit");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        final String status = jsonObject.getString("status");
        final String orderid = jsonObject.getString("orderid");
        final String notice = jsonObject.getString("notice");
        final String update_time = jsonObject.getString("updata_time");
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("status", status);
        hashMap.put("orderid", orderid);
        hashMap.put("notice", notice);
        hashMap.put("update_time", update_time);
        intent.putExtra("params", hashMap);
    }

    //余额解析
    private void formatMoney(Intent intent, JSONObject jsonObject) throws JSONException {
        intent.setClass(MyIntentService.this, EnCash.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        String money = jsonObject.getString("money");
        intent.putExtra("money", money);
    }

    //问题详情解析
    private void formatDialog(Intent intent, JSONObject jsonObject) throws JSONException {
        final String dialogid = jsonObject.getString("dialogid");
        final String type = jsonObject.getString("type");
        final String state = jsonObject.getString("state");
        intent.putExtra("dialogId", dialogid);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if ("free".equals(type)) {
            intent.setClass(MyIntentService.this, QuestionDetail.class);
        } else {
            if ("正常".equals(state)) {
                intent.setClass(MyIntentService.this, QuestionDetail.class);
            } else {
                intent.setClass(MyIntentService.this, VipQuestionDetail.class);
            }
        }
        intent.putExtra("type", "my");
        intent.putExtra("state", state);
    }

    //app在否前台
    private boolean isRunningForeground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(getPackageName())) {
            return true;
        }
        return false;
    }

    private void notifyPersonalInfo() {
        Intent i = new Intent(Constant.ACTION_UPDATE_PERSONAL_INFO);
        sendBroadcast(i);
    }

}